package com.kfh.ybracelet.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.CircleOptions;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.kfh.ybracelet.R;
import com.kfh.ybracelet.base.BaseFragment;
import com.kfh.ybracelet.bean.Child;
import com.kfh.ybracelet.bean.ChildAndWatchInforResult;
import com.kfh.ybracelet.bean.LocationBean;
import com.kfh.ybracelet.location.ChooseLocationBabyActivity;
import com.kfh.ybracelet.location.HistoryActivity;
import com.kfh.ybracelet.location.InviteActivity;
import com.kfh.ybracelet.location.SafeAreaActivity;
import com.kfh.ybracelet.location.SnCodeActivity;
import com.kfh.ybracelet.location.WatchStatusActivity;
import com.kfh.ybracelet.location.WhiteListActivity;
import com.kfh.ybracelet.my.AddBabyActivity;
import com.kfh.ybracelet.net.HttpUtil;
import com.kfh.ybracelet.utils.AbDateUtil;
import com.kfh.ybracelet.utils.CommonUtils;
import com.kfh.ybracelet.utils.Constant;
import com.kfh.ybracelet.utils.LogUtil;
import com.kfh.ybracelet.widget.BatteryView;

import org.json.JSONException;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 定位fragment
 * Created by Administrator on 2015/7/20.
 */
public class LocationFragment extends BaseFragment implements View.OnClickListener, AMap.InfoWindowAdapter {

    private AMap aMap;
    private MapView mapView;
    private AMapLocationClient mLocationClient;
    private ProgressDialog settingDialog;
    private Intent mIntent;
    private ProgressDialog progressDialog;
    private TextView tv_title_name;
    private TextView tv_title;
    private TextView tv_child_location;
    private TextView tv_watch_battery;
    private TextView tv_location_type;
    private TextView tv_status;
    private BatteryView mBatteryView;
    private ImageView iv_location_type;
    private ImageView iv_status;
//    //当前选择的孩子的数据

    private final static int LOCATION_MSG_CODE_TEN = 0x99;//定位handle message code  GSM 和 ""
    private String location_type = ""; // 定位类型,  点击导航栏
    private static final String LOCATION_TYPE_LOC = "loc";//loc 定位
    private static final String LOCATION_TYPE_GPS = "gps";//gps 定位

    public List<Child> childList = new ArrayList<>();

    private String babyName;
    //    private InfoWindow myInfoWindow;
    private double babyStuLat;
    private double babyStuLng;
    private RelativeLayout rl_no_baby;
    private TextView tv_add;
    private ImageView iv_left;
    private LocationBean.LocationChildInfo childInfo = null;
    private final static long LOCATION_INTERVAL_TIME = 30 * 1000;//定位间隔 30秒
    //    private boolean isDelay = false; //是否需要延迟30秒发送定位请求
    private boolean firstLoc = true; //是否是第一次loc请求
    private String curPhoneNum;//当前老人的手表号码
    private LinearLayout ll_location;
    private boolean online;//手表是否在线

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_location, null);

        EventBus.getDefault().register(this);

        firstLoc = true;//第一次loc 定位请求
        curPhoneNum = "";//当前老人的手机号码置为空

//        // 构建Marker图标
//        mBitmap = BitmapDescriptorFactory.fromResource(R.mipmap.thumb);

        initWidget(view);

        mapView = (MapView) view.findViewById(R.id.gdmap);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        initMap();

        return view;
    }

    private String TAG = getClass().getSimpleName();


    /**
     * 初始化
     */
    private void initMap() {
//        if (aMap == null) {
        aMap = mapView.getMap();
//            setUpMap();
//        }

        //mark的点击事件
        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {

                Log.e(TAG, " +++ onMarkerClick +++ ");
                mLocMarker = marker;
                return false;
            }
        });

        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                if (mLocMarker.isInfoWindowShown())
                    mLocMarker.hideInfoWindow();//这个是隐藏infowindow窗口的方法
            }
        });

        aMap.setInfoWindowAdapter(this);

        //显示比例尺
        aMap.getUiSettings().setScaleControlsEnabled(true);

//        float scalePerPixel = aMap.getScalePerPixel();
//        Projection projection = aMap.getProjection();

//        aMap.setInfoWindowAdapter(new AMap.InfoWindowAdapter() {
//            @Override
//            public View getInfoWindow(Marker marker) {
//                if (infoView == null) {
//                    infoView = new TextView(getActivity());
//                    infoView.setGravity(Gravity.CENTER);
//                    infoView.setBackgroundResource(R.mipmap.ic_mylocation_bg);
//                }
//                infoView.setText(babyName);
//                Log.e(TAG, "****** getInfoWindow ********");
//                return infoView;
//            }
//
//            @Override
//            public View getInfoContents(Marker marker) {
//                if (infoView == null) {
//                    infoView = new TextView(getActivity());
//                    infoView.setGravity(Gravity.CENTER);
//                    infoView.setBackgroundResource(R.mipmap.ic_mylocation_bg);
//                }
//                infoView.setText(babyName);
//                Log.e(TAG, "****** getInfoContents ********");
//                return infoView;
//            }
//        });
//        mSensorHelper = new SensorEventHelper(this);
//        if (mSensorHelper != null) {
//            mSensorHelper.registerSensorListener();
//        }
    }

    //    @Override
    public void deactivate() {
//        mListener = null;
        if (mLocationClient != null) {
            mLocationClient.stopLocation();
            mLocationClient.onDestroy();
        }
        mLocationClient = null;
    }

    @Override
    public void onResume() {
        super.onResume();

        LogUtil.e(TAG, "===== onResume =====");

        if (mapView != null)
            mapView.onResume();

        tv_title.setText(sp.getString(Constant.CURRENTCHILDNAME, ""));

        if (handle != null)
            handle.removeCallbacksAndMessages(null);
        firstLoc = true;
        locationBaby();//定位孩子位置

    }

    /**
     * 定位孩子位置
     */
    private void locationBaby() {

        if (!CommonUtils.isNull(sp.getString(Constant.CURRENTCHILDID, ""))) {//当前有选中的孩子
            //先判断权限是否够

            if (Constant.POWER_ADMIN == sp.getInt(Constant.LEVEL, -1) || Constant.POWER_PARENT == sp.getInt(Constant.LEVEL, -1)) {

//                isDelay = true;// getChildernAndWatch 方法 需要延迟 30秒 再发, 因为此次已经请求了一次
//
//                location_type = LOCATION_TYPE_LOC;//定位模式切换成loc
//                //有权限, 获取孩子数据
//                handle.post(runnable);

                getBabyLocation(LOCATION_TYPE_LOC, false);//loc模式定位

            } else {
                pageNoPermission();
                showToast(getResources().getString(R.string.have_no_right));
            }

        } else { //没有选择过孩子

//            isDelay = false;//getChildernAndWatch方法 不需要延迟

            //获取所有孩子信息  和 权限
            getChildernAndWatch();

        }

    }

    /**
     * 没有权限的页面
     */
    private void pageNoPermission() {
        // 没有权限
        tv_add.setVisibility(View.GONE);//添加手表的按钮消失
        rl_no_baby.setVisibility(View.VISIBLE);
        ll_location.setVisibility(View.INVISIBLE);
        iv_left.setVisibility(View.GONE);
    }

    /**
     * 有权限 有sn码  正常定位
     */
    private void pageWithPermissionAndSN() {
        rl_no_baby.setVisibility(View.INVISIBLE);
        ll_location.setVisibility(View.VISIBLE);
        iv_left.setVisibility(View.VISIBLE);
    }

    /**
     * 有权限但是没有sn码
     */
    private void pageWithPermissionNoSN() {
        rl_no_baby.setVisibility(View.VISIBLE);
        ll_location.setVisibility(View.INVISIBLE);
        tv_add.setVisibility(View.VISIBLE);
        iv_left.setVisibility(View.GONE);
    }

    /**
     * 没有权限的页面
     */
    private void pageWithPermission() {
        rl_no_baby.setVisibility(View.INVISIBLE);
        ll_location.setVisibility(View.VISIBLE);
        iv_left.setVisibility(View.VISIBLE);
    }

    @Override
    public void onPause() {
        super.onPause();

        if (mapView != null)
            mapView.onPause();
        deactivate();

    }

    /**
     * 方法必须重写
     */
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mapView != null)
            mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        if (mapView != null)
            mapView.onDestroy();

//        if (mLocationClient != null)
//            mLocationClient.onDestroy();

        //移除runnable
        if (handle != null) {
            handle.removeCallbacksAndMessages(null);
        }

        EventBus.getDefault().unregister(this);

//        Log.e(TAG, " ''''''' ondestory ''''''' ");

    }

//    @Override
//    public void onStop() {
//        super.onStop();
//        mLocationClient.stopLocation();
//    }

    /**
     * 切换宝宝
     *
     * @param isChange 是否切换了宝宝
     */
    public void onEventMainThread(Boolean isChange) {

        LogUtil.e(TAG, "是否切换了老人===== : " + isChange);

        if (isChange) {//切换了宝宝

            curPhoneNum = "";//当前老人的手机号码置为空
            noLocation();//清空当前显示的位置信息

            babyStuLat = 0;//定位信息 重置
            babyStuLng = 0;

            if (handle != null) {

                //移除所有的message 和 runnable
                handle.removeCallbacksAndMessages(null);

//                delay = 0;
                //第一次 loc 定位
                firstLoc = true;
                location_type = LOCATION_TYPE_LOC;
                handle.post(runnable);
//                handle.postDelayed(runnable, LOCATION_INTERVAL_TIME);
//                handle.postDelayed(gpsRun, LOCATION_INTERVAL_THITRY);

            }

        }

    }

    private Handler handle = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case LOCATION_MSG_CODE_TEN:

//                    //让地图定位到孩子位置
//                    if (moveTolocation(msg)) return;

                    if (handle != null) {
//                        handle.removeCallbacks(runnable);//先移除掉该runnanble
//                    handle.removeCallbacksAndMessages(null);
                        handle.postDelayed(runnable, LOCATION_INTERVAL_TIME);
                    }

                    break;

            }
        }
    };

    /**
     * 点击底部导航栏 重新定位
     */
    public void reBottonLocation() {

        LogUtil.e(TAG, "   ==== 点击底部定位模块 重新定位 ====   " + babyStuLat + ",babyStuLng:" + babyStuLng);
        location_type = LOCATION_TYPE_LOC;
        location(babyStuLat, babyStuLng);
        getBabyLocation(location_type, true);

    }

    /**
     * //让地图定位到孩子位置
     *
     * @param childInfo
     * @return
     */
    private void moveTolocation(LocationBean.LocationChildInfo childInfo) {

        this.childInfo = childInfo;

        if (childInfo == null || childInfo.device == null)
            return;

        setBabyData(childInfo);

        if (aMap == null)
            return;

        try {

            aMap.clear();

            if (!CommonUtils.isNull(childInfo.device.latitude) && !CommonUtils.isNull(childInfo.device.longitude)) {

                babyStuLat = Double.parseDouble(childInfo.device.latitude);
                babyStuLng = Double.parseDouble(childInfo.device.longitude);

                location(babyStuLat, babyStuLng);
            }
//            else {
////                MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(12.0f);
////                mBaiduMap.setMapStatus(msu);
////
//////                LogUtil.e("tag", "我的坐标:" + mApplication.myLatitude + ",: " + mApplication.myLongitude);
////                if (mApplication.myLatitude != 0 && mApplication.myLongitude != 0)
////                    locationMy(mApplication.myLatitude, mApplication.myLongitude);
//            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 定位到坐标点
     *
     * @param lat
     * @param lng
     */
    private void location(Double lat, Double lng) {

        Log.e(TAG, "地图定位到坐标点 !!~~~~~~~~~~~~~");

        if (!isAdded()) {//如果当前的fragment被销毁了
            if (handle != null)
                handle.removeCallbacksAndMessages(null);
            return;
        }

        try {
            if (aMap == null)
                return;
            aMap.clear();
//            point = new LatLng(lat, lng);

            LatLng location = new LatLng(lat, lng);
            addCircle(location, 100f);//添加定位精度圈
            addMarker(location);
            aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(location, 18));//移动到location位置,并设置缩放比例

//            option = new MarkerOptions().position(point).icon(mBitmap).zIndex(5);
//            marker = (Marker) (mBaiduMap.addOverlay(option));
//            // 定位到该点
//            u = MapStatusUpdateFactory.newLatLng(point);
//            if (mBaiduMap != null)
//                mBaiduMap.setMapStatus(u);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private Marker mLocMarker;
    BitmapDescriptor des = null;
    private static final int STROKE_COLOR = Color.argb(180, 3, 145, 255);
    private static final int FILL_COLOR = Color.argb(10, 0, 0, 180);
//    private Circle mCircle;

    private void addCircle(LatLng latlng, double radius) {

//        Log.e(TAG, "精度圈的大小:" + radius);

        CircleOptions options = new CircleOptions();
        options.strokeWidth(1f);
//        options.fillColor(getResources().getColor(R.color.color_location));
        options.fillColor(FILL_COLOR);
        options.strokeColor(STROKE_COLOR);
        options.center(latlng);
        options.radius(radius);
        aMap.addCircle(options);
    }

    private void addMarker(LatLng latlng) {

//        if (des == null) {
//            Bitmap bMap = BitmapFactory.decodeResource(this.getResources(),
//                    R.mipmap.thumb);
//            des = BitmapDescriptorFactory.fromBitmap(bMap);
//        }

        mLocMarker = aMap.addMarker(new MarkerOptions().position(latlng)
                .title(babyName)
                .icon(BitmapDescriptorFactory.fromBitmap(BitmapFactory.decodeResource(getResources(), R.mipmap.thumb))).anchor(0.5f, 0.5f));
//		BitmapDescriptor des = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked);
//        MarkerOptions options = new MarkerOptions();
//        options.icon(des);
//        options.anchor(0.5f, 0.5f);
//        options.position(latlng);
//        mLocMarker = aMap.addMarker(options);
//        mLocMarker.setTitle(babyName);
    }

    //GSM 定位
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {

//            LogUtil.e(TAG, "请求一次  GSM  定位,该线程的名字:" + Thread.currentThread().getName());

//            LogUtil.e(TAG, " 是否添加 : " + isAdded());

            if (!isAdded()) { //fragment 被销毁了
                if (handle != null)
                    handle.removeCallbacksAndMessages(null);
                return;
            }

            //获取宝宝的位置
            getBabyLocation(location_type, false);

        }
    };


    private void locationErr() {

        rl_no_baby.setVisibility(View.VISIBLE);
        ll_location.setVisibility(View.INVISIBLE);
        iv_left.setVisibility(View.GONE);
        tv_add.setVisibility(View.GONE);

    }

    private ProgressDialog locationIng;

    /**
     * 获取宝宝的位置 (真正定位接口)
     *
     * @param type 定位类型  gps or ""
     */
    private void getBabyLocation(final String type, boolean isShow) {

        if (!CommonUtils.isNetworkAvailable(getActivity())) {
            reLocation();//重新定位孩子的位置
            LogUtil.e(TAG, "  ===  网络不可用  === ");
            return; //网络不可用 直接返回
        }

        if (isShow) {
            locationIng = ProgressDialog.show(getActivity(), "", "定位中...");
            locationIng.setCancelable(true);
        }

        LogUtil.e(TAG, "   ===== 获取定位信息一次 =====   " + type);

        final JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("id", sp.getString(Constant.CURRENTCHILDID, ""));
        j.put("locationtype", type);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.WEB_ROOT + Constant.GETCHILDLOC, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {

                if (locationIng != null && locationIng.isShowing())
                    locationIng.dismiss();

                location_type = "";//把定位模式设置成 "" 模式

                if (LOCATION_TYPE_GPS.equals(type)) {//gps定位 无需操作, 只是请求而已
//                    LogUtil.e(TAG, "==== gps 定位 ====");
                    return;
                }

                if (LOCATION_TYPE_LOC.equals(type)) {//如果是loc定位, 第一次loc定位定位孩子的位置,其余的不定位孩子的位置

//                    LogUtil.e(TAG, "==== loc 定位 ====");

                    if (!firstLoc) { //如果不是第一次 loc模式的 定位  则不定位孩子位置
                        return;
                    } else { //如果是第一次定位, 修改值为false, 然后继续 定位孩子位置
                        firstLoc = false;
                    }

                }

                showLocation(response); //定位到孩子的位置

                reLocation();//重新定位孩子的位置

            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                LogUtil.e(TAG, "孩子定位信息fail");

                if (locationIng != null && locationIng.isShowing())
                    locationIng.dismiss();

                //孩子定位数据失败,30s后重新定位
                handle.postDelayed(runnable, LOCATION_INTERVAL_TIME);
            }

        }) {

            protected Map<String, String> getParams() {
                Map<String, String> param = new HashMap<String, String>();
                param.put("data", j.toJSONString());

                return param;
            }

        };

        //把请求加入队列
        mApplication.addToRequestQueue(stringRequest, getClass().getName());

    }

    /**
     * 定位老人位置
     *
     * @param response
     */
    private void showLocation(String response) {

        LogUtil.e(TAG, "老人定位信息:" + response);

        try {

            LocationBean locationResutl = JSONObject.parseObject(response, LocationBean.class);

            if (locationResutl == null)  //没有位置信息,则不做处理, 让子线程继续请求
                return;

            if (Constant.STATUS_SUCCESS == locationResutl.code) {

                if (locationResutl.data == null || locationResutl.data.size() < 1) {
                    locationErr();
                    return;
                }

                //获取到该宝宝信息
                LocationBean.LocationChildInfo currentChild = locationResutl.data.get(0);

                if (currentChild == null || currentChild.device == null) { //防止出错
                    locationErr();
                    return;
                }

                //当前的手表电话号码
                curPhoneNum = currentChild.device.phoneNum;

                //先判断sn码是否存  再判断等级是否够
                if (!CommonUtils.isNull(currentChild.device.sn)) {

                    //管理员和亲人 并且有sn码   有权限
                    if (Constant.POWER_ADMIN == sp.getInt(Constant.LEVEL, 0) || Constant.POWER_PARENT == sp.getInt(Constant.LEVEL, 0)) {
//                    if (Constant.POWER_ADMIN == currentChild.level || Constant.POWER_PARENT == currentChild.level) {
                        pageWithPermission();
                    } else {
                        //朋友 没有权限   showToast("权限等级不够,请联系管理员");
                        pageNoPermission();
                        return;
                    }

                } else {
                    //没有手表   showToast("请给孩子绑定手表");
                    pageWithPermissionNoSN();
                    return;
                }

                //让地图定位到孩子位置
                moveTolocation(currentChild);

            } else {

                if (locationResutl.code == Constant.FA_PHNOEKEY_ERROR) {//如果是TOKEN 错误, 提示重新登录
                    showToast(Constant.showErrorMsg(locationResutl.code, getActivity()));
                    return;
                } else if (Constant.FA_RIGHT_ERROR == locationResutl.code) {
                    //没有权限
//                            showToast("权限等级不够,请联系孩子管理员");
                    pageNoPermission();

                }

                //请求数据失败
                locationErr();

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 30秒后重新定位孩子的位置
     */
    private void reLocation() {
        //30秒定位
        Message msg = Message.obtain();
        msg.what = LOCATION_MSG_CODE_TEN;
        handle.sendMessage(msg);
    }

    private void initWidget(View view) {

        iv_left = (ImageView) view.findViewById(R.id.iv_left);
        ImageView iv_right = (ImageView) view.findViewById(R.id.iv_right);
        tv_title = (TextView) view.findViewById(R.id.tv_title);

        tv_title.setText(getResources().getString(R.string.location));

        ImageView iv_location = (ImageView) view.findViewById(R.id.iv_location);
        ImageView iv_call = (ImageView) view.findViewById(R.id.iv_call);
        ImageView iv_history = (ImageView) view.findViewById(R.id.iv_history);
        ImageView iv_share = (ImageView) view.findViewById(R.id.iv_share);
//        ImageView iv_inquire = (ImageView) view.findViewById(R.id.iv_inquire);
        //广告页
        rl_no_baby = (RelativeLayout) view.findViewById(R.id.rl_no_baby);
        tv_add = (TextView) view.findViewById(R.id.tv_add);

        tv_add.setOnClickListener(this);
        //当前显示的孩子的信息
        tv_title_name = (TextView) view.findViewById(R.id.tv_title_name);
//        tv_time = (TextView) view.findViewById(R.id.tv_time);
        tv_child_location = (TextView) view.findViewById(R.id.tv_child_location);
        tv_watch_battery = (TextView) view.findViewById(R.id.tv_watch_battery);
        tv_location_type = (TextView) view.findViewById(R.id.tv_location_type);
        tv_status = (TextView) view.findViewById(R.id.tv_status);
        iv_status = (ImageView) view.findViewById(R.id.iv_status);
        mBatteryView = (BatteryView) view.findViewById(R.id.bv_battery);
        iv_location_type = (ImageView) view.findViewById(R.id.iv_location_type);
        ll_location = (LinearLayout) view.findViewById(R.id.ll_location);

        iv_left.setOnClickListener(this);
        iv_right.setOnClickListener(this);

        iv_location.setOnClickListener(this);
//        iv_inquire.setOnClickListener(this);
        iv_call.setOnClickListener(this);
        iv_history.setOnClickListener(this);
        iv_share.setOnClickListener(this);

    }

    @Override
    public void onClick(View view) {

        if (settingDialog != null && settingDialog.isShowing())
            settingDialog.dismiss();

        switch (view.getId()) {

            case R.id.iv_left://手表设置

                showSetting();

                break;
            case R.id.iv_right://切换老人

                mIntent = new Intent(getActivity(), ChooseLocationBabyActivity.class);
                startActivity(mIntent);

                break;
            case R.id.iv_location://定位 请求gps定位

                //定位到老人位置
                if (babyStuLat != 0 && babyStuLng != 0)
                    location(babyStuLat, babyStuLng);

                //调用接口 传递 gps 参数
                getBabyLocation(LOCATION_TYPE_GPS, true);

                break;

            case R.id.iv_share://分享

                if (CommonUtils.isNull(sp.getString(Constant.CURRENTCHILDID, ""))) {
                    showToast(getResources().getString(R.string.please_choose_old_first));
                    return;
                }

                //邀请码
                mIntent = new Intent(getActivity(), InviteActivity.class);
//                mIntent.putExtra("childId", sp.getString(Constant.CURRENTCHILDID, ""));
                startActivity(mIntent);

                break;

            case R.id.tv_add://添加SN码

                mIntent = new Intent(getActivity(), SnCodeActivity.class);
                startActivity(mIntent);

                break;

            case R.id.iv_call://拨打电话

                if (CommonUtils.isNull(curPhoneNum)) {
                    showToast(getResources().getString(R.string.please_bind_num));
                    return;
                }

                if (curPhoneNum != null)

                    new AlertDialog.Builder(getActivity()).setMessage(curPhoneNum).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).setPositiveButton("呼叫", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            dialog.dismiss();

                            if (CommonUtils.isNull(curPhoneNum)) {
                                showToast("请给手表安装SIM卡,并在手表状态页面设置");
                                return;
                            }

                            //拨打电话
                            Intent intent = new Intent("android.intent.action.CALL", Uri.parse("tel:" + curPhoneNum));
                            startActivity(intent);

                        }
                    }).show();

                break;
            case R.id.iv_history://历史轨迹

                mIntent = new Intent(getActivity(), HistoryActivity.class);
                startActivity(mIntent);
                break;

            case R.id.tv_safe_area://安全区域

                if (CommonUtils.isNull(sp.getString(Constant.CURRENTCHILDID, ""))) {
                    showToast(getResources().getString(R.string.please_bind_old_first));
                    return;
                }

                mIntent = new Intent(getActivity(), SafeAreaActivity.class);
//                mIntent.putExtra("id", currentShowBaby.id);
                startActivity(mIntent);
                break;

            case R.id.tv_white_list://手环白名单

                if (CommonUtils.isNull(sp.getString(Constant.CURRENTCHILDID, ""))) {
                    showToast(getResources().getString(R.string.please_bind_old_first));
                    return;
                }
                mIntent = new Intent(getActivity(), WhiteListActivity.class);
//                mIntent.putExtra("sn", currentShowBaby.sn);
//                mIntent.putExtra("watchId", currentShowBaby.id);
                startActivity(mIntent);

                break;
            case R.id.tv_state://手表设置

                if (childInfo == null) {
                    showToast(getResources().getString(R.string.please_bind_old_first));
                    return;
                }

                mIntent = new Intent(getActivity(), WatchStatusActivity.class);
                mIntent.putExtra("child", (Serializable) childInfo);
                startActivity(mIntent);

                break;
            case R.id.tv_unbind://解绑手表

                if (CommonUtils.isNull(sp.getString(Constant.CURRENTCHILDID, ""))) {
                    showToast(getResources().getString(R.string.please_bind_old_first));
                    return;
                }

                showUnwrapWatchDialog();
                break;

            case R.id.tv_find_watch://查找手表

                if (CommonUtils.isNull(sp.getString(Constant.CURRENTCHILDID, ""))) {
                    showToast(getResources().getString(R.string.please_bind_old_first));
                    return;
                }

                if (!online) {
                    showToast("当前手表关机,无法查找手表");
                    return;
                }

                findWatch();

                break;

//            case iv_inquire:
//
//                mIntent = new Intent(getActivity(), InquireActivity.class);
//                startActivity(mIntent);
//
//                break;

        }
    }

    /**
     * 查找手表, 手表响铃
     */
    private void findWatch() {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));
        j.put("id", sp.getString(Constant.CURRENTCHILDID, ""));

        HttpUtil.setPostRequest("准备中...", getActivity(), Constant.WEB_ROOT + Constant.FINDWATCH, j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {

            @Override
            public void setOnSuccessListener(String str) {

                try {
                    org.json.JSONObject result = new org.json.JSONObject(str);

                    Constant.showErrorMsg(result.getInt("code"), getActivity());

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        }, null);

    }

    /**
     * 手表设置
     */
    private void showSetting() {

        settingDialog = new ProgressDialog(getActivity());
        settingDialog.setCanceledOnTouchOutside(true);
        settingDialog.show();
        settingDialog.setContentView(R.layout.dialog_setting);

        TextView tv_safe_area = (TextView) settingDialog.findViewById(R.id.tv_safe_area);
        TextView tv_white_list = (TextView) settingDialog.findViewById(R.id.tv_white_list);
        TextView tv_state = (TextView) settingDialog.findViewById(R.id.tv_state);
        TextView tv_unbind = (TextView) settingDialog.findViewById(R.id.tv_unbind);
        TextView tv_find_watch = (TextView) settingDialog.findViewById(R.id.tv_find_watch);

        tv_safe_area.setOnClickListener(this);
        tv_white_list.setOnClickListener(this);
        tv_state.setOnClickListener(this);
        tv_unbind.setOnClickListener(this);
        tv_find_watch.setOnClickListener(this);

    }

    /**
     * 弹出提示解除绑定手表的对话框
     */
    private void showUnwrapWatchDialog() {

        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setCanceledOnTouchOutside(true);
        progressDialog.show();
//        View view = View.inflate(getActivity(), R.layout.item_show_remind, null);
        progressDialog.setContentView(R.layout.item_show_remind);
        TextView tv_confirm = (TextView) progressDialog.findViewById(R.id.tv_confirm);
        TextView tv_cancel = (TextView) progressDialog.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }
            }
        });

        tv_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                unwrapWatch();

                if (progressDialog != null && progressDialog.isShowing()) {
                    progressDialog.dismiss();
                }

            }
        });

    }

    //解绑手表
    private void unwrapWatch() {

        JSONObject j = new JSONObject();
//        if (currentShowBaby != null)
        j.put("id", sp.getString(Constant.CURRENTCHILDID, ""));
        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest("解绑中...", getActivity(), Constant.WEB_ROOT + Constant.UNBINDWTACH, j.toJSONString(),
                getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            org.json.JSONObject result = new org.json.JSONObject(str);

//                            if (result.getInt("code") == Constant.STATUS_SUCCESS) {
                            showToast("解绑成功");
                            getChildernAndWatch();
//                            } else {
//                                showToast(Constant.showErrorMsg(result.getInt("code"), getActivity()));
//                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
                }, null);
    }

//    /**
//     * 定位SDK监听函数
//     */
//    public class MyLocationListenner implements BDLocationListener {
//
//        @Override
//        public void onReceiveLocation(BDLocation location) {
//            // map view 销毁后不在处理新接收的位置
//            if (location == null || mMapView == null)
//                return;
////            MyLocationData locData = new MyLocationData.Builder().accuracy(location.getRadius())
////                    // 此处设置开发者获取到的方向信息，顺时针0-360
////                    .direction(100).latitude(location.getLatitude())
////                    .longitude(location.getLongitude()).build();
//
//            mApplication.myLatitude = location.getLatitude();
//            mApplication.myLongitude = location.getLongitude();
//
////            mBaiduMap.setMyLocationData(locData);
//
//        }
//
//    }

    private TextView infoView;

//    /**
//     * 显示我的位置
//     *
//     * @param latLng
//     */
//    private void showMyLocationInfo(LatLng latLng) {
//
//        if (infoView == null) {
//            infoView = new TextView(getActivity());
//            infoView.setGravity(Gravity.CENTER);
//            infoView.setBackgroundResource(R.mipmap.ic_mylocation_bg);
//        }
//        infoView.setText("我的位置");
//        InfoWindow myInfoWindow = new InfoWindow(infoView, latLng, 10);
//        mBaiduMap.showInfoWindow(myInfoWindow);
//
//    }

//    /**
//     * 显示老人的信息
//     *
//     * @param latLng
//     */
//    private void showBabyLocationInfo(LatLng latLng) {
//
//        if (infoView == null) {
//            infoView = new TextView(getActivity());
//            infoView.setGravity(Gravity.CENTER);
//            infoView.setBackgroundResource(R.mipmap.ic_mylocation_bg);
//        }
//
//        infoView.setText(babyName);
//        myInfoWindow = new InfoWindow(infoView, latLng, -10);
//        mBaiduMap.showInfoWindow(myInfoWindow);
//
//    }

    private void getChildernAndWatch() {

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.TOKEN, ""));

        HttpUtil.setPostRequest("获取数据中...", getActivity(), Constant.WEB_ROOT + Constant.GETCHILDERNANDEWATCH,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {

                    @Override
                    public void setOnSuccessListener(String str) {
                        try {

                            ChildAndWatchInforResult result = JSONObject.parseObject(str, ChildAndWatchInforResult.class);

//                            if (result.code == Constant.STATUS_SUCCESS) {

                            if (result.data == null) {

                                locationErr();
                                showToast(getResources().getString(R.string.no_bind_old_data));
                                return;
                            }

                            if (result.data.size() > 0) {

                                childList = result.data;

                                if (childList == null) {
                                    showToast(getResources().getString(R.string.no_bind_old_data));
                                    locationErr();
                                    return;
                                }

                                Child currentShowBaby = childList.get(0);//默认选择第一个

                                if (currentShowBaby == null) {
                                    locationErr();
                                    return;
                                }

                                //sp中存储默认的第一个
                                SharedPreferences.Editor edit = sp.edit();
                                edit.putString(Constant.CURRENTCHILDID, currentShowBaby.id);
                                edit.putString(Constant.CURRENTCHILDNAME, currentShowBaby.name);
                                edit.putInt(Constant.LEVEL, currentShowBaby.level);
                                tv_title.setText(currentShowBaby.name);
                                edit.apply();

                                if (Constant.POWER_ADMIN == currentShowBaby.level || Constant.POWER_PARENT == currentShowBaby.level) {

                                    //先判断等级是否够  再判断sn码是否存在
                                    if (!CommonUtils.isNull(currentShowBaby.device.sn)) {
                                        //管理员和亲人 并且有sn码   有权限, 可以获取孩子的位置信息

                                        //请求孩子定位数据
                                        if (handle != null) {
//                                                delay = 0;
//                                                if (isDelay) { // 如果有选择过孩子 则需要延迟发送定位请求(因为有发过定位请求)
//
//                                                    isDelay = false;
//                                                    handle.postDelayed(runnable, LOCATION_INTERVAL_TIME);
//
//                                                } else {
                                            handle.post(runnable);
//                                                }

                                        }

                                    } else {
                                        //有权限 没有手表

                                        showToast(getResources().getString(R.string.please_bind_watch));
                                        pageWithPermissionNoSN();

                                        return;
                                    }

                                    //正常定位状态
                                    pageWithPermissionAndSN();

                                } else {
                                    //朋友权限 没有权限
                                    showToast(getResources().getString(R.string.have_no_right));
                                    pageNoPermission();

                                }

                            } else {
                                //没有绑定过老人 (跳到绑定老人的页面)
                                mIntent = new Intent(getActivity(), AddBabyActivity.class);
                                mIntent.putExtra("cancle", false);
                                startActivity(mIntent);
                            }

                        } catch (Exception e) {
                            showToast(Constant.NODATA);
                            e.printStackTrace();
                        }
                    }
                }, null);
    }

    private void noLocation() {

        tv_title_name.setText("");

        mBatteryView.setPower(0);

        tv_location_type.setText("暂无定位");
        iv_location_type.setImageBitmap(null);

        tv_status.setText("");
        iv_status.setImageBitmap(null);
    }

    private void setBabyData(LocationBean.LocationChildInfo babyInfo) {

        if (babyInfo == null || babyInfo.device == null)
            return;

        babyName = babyInfo.name;
        tv_title_name.setText(CommonUtils.isNull(babyName) ? "" : babyName + "  " + AbDateUtil.getStringByFormat(babyInfo.device.updateTime, AbDateUtil.dateFormatYMDHMS));
        tv_title.setText(CommonUtils.isNull(babyName) ? "" : babyName);
//                        tv_time.setText(date.toLocaleString());

        tv_child_location.setText(CommonUtils.isNull(babyInfo.device.location) ? "暂无位置信息" : babyInfo.device.location);
        if (!CommonUtils.isNull(babyInfo.device.battery)) {
            tv_watch_battery.setText(babyInfo.device.battery + "%");
            int currentBattery = Integer.parseInt(babyInfo.device.battery);
            if (currentBattery <= 20) {//电量小于20变红
                mBatteryView.setLength(35, 15, 5, 10, 1);
                mBatteryView.setColor(Color.BLACK, Color.RED);

            } else { //大于20是绿的

                mBatteryView.setLength(35, 15, 5, 10, 1);
                mBatteryView.setColor(Color.BLACK, Color.GREEN);
            }

            if (currentBattery <= 5) {
                mBatteryView.setPower(5);
            } else {
                mBatteryView.setPower(currentBattery);
            }

        }

        if ("gsm".equals(babyInfo.device.provider)) {//基站定位

            tv_location_type.setText("基站定位");
            iv_location_type.setImageResource(R.mipmap.location_station);

        } else if ("gps".equals(babyInfo.device.provider)) {//gps定位

            tv_location_type.setText("GPS定位");
            iv_location_type.setImageResource(R.mipmap.location_gps);

        } else if ("wifi".equals(babyInfo.device.provider)) {//wifi定位

            tv_location_type.setText("WIFI定位");
            iv_location_type.setImageResource(R.mipmap.location_wifi);
        } else {
            tv_location_type.setText("暂无定位");
        }

        if (babyInfo.device.gsm == 0) {
            iv_status.setImageResource(R.mipmap.signal_zero);
        } else if (babyInfo.device.gsm <= 20) {
            iv_status.setImageResource(R.mipmap.signal_twenty);
        } else if (babyInfo.device.gsm <= 40) {
            iv_status.setImageResource(R.mipmap.signal_fourty);
        } else if (babyInfo.device.gsm <= 60) {
            iv_status.setImageResource(R.mipmap.signal_sixty);
        } else if (babyInfo.device.gsm <= 99) {
            iv_status.setImageResource(R.mipmap.signal_eighty);
        } else if (babyInfo.device.gsm == 100) {
            iv_status.setImageResource(R.mipmap.signal_full);
        }

        online = babyInfo.device.online;

        tv_status.setText(babyInfo.device.online ? "在线" : "离线");

    }

    @Override
    public View getInfoWindow(Marker marker) {
        Log.e(TAG, "****** getInfoWindow ********");
        if (infoView == null) {
            infoView = new TextView(getActivity());
            infoView.setGravity(Gravity.CENTER);
            infoView.setBackgroundResource(R.mipmap.ic_mylocation_bg);
        }
        infoView.setText(babyName);
        return infoView;
    }

    @Override
    public View getInfoContents(Marker marker) {
//        if (infoView == null) {
//            infoView = new TextView(getActivity());
//            infoView.setGravity(Gravity.CENTER);
//            infoView.setBackgroundResource(R.mipmap.ic_mylocation_bg);
//            infoView.setText(babyName);
//        }
        Log.e(TAG, "****** getInfoWindow ********");

        if (infoView == null) {
            infoView = new TextView(getActivity());
            infoView.setGravity(Gravity.CENTER);
            infoView.setBackgroundResource(R.mipmap.ic_mylocation_bg);
        }
        infoView.setText(babyName);
        return infoView;
    }
}